﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Solidi
{
    sealed class CircularDependency
    {
		private IDependencyKey _key;
        private IList<IDependency> _dependencies;
        private int _index;

		public CircularDependency(IDependencyKey key)
        {
            _key = key;
        }

		public bool IsCircular(IDependencyKey key)
        {
            return _key.Equals(key);
        }

        public object ResolvePrevious(IDependencyContext container)
        {
            if (_dependencies == null)
            {
                _dependencies = container.Registry.Find(_key);

                _index = _dependencies.Count - 1;
            }

            if (--_index < 0)
            {
                return null;
            }

            return container.Lifetime.Resolve(container, _dependencies[_index]);
        }
    }
}
